<template>
  <view class="systemMessage">
    <myHead title="系统消息" :right="false" />
    <scroll-view :scroll-y="true" class="scroll" @scrolltoupper="scrolltoupper">
      <template v-for="(item, key) in messageList">
        <realName
          :key="key"
          :extension="JSON.parse(item.payload.extension)"
          :time="item.time"
        />
      </template>
    </scroll-view>
  </view>
</template>

<script>
import realName from "@/pages/Huicover/systemMessage/tem/realName";
// import logger from "@/utils/logger";
export default {
  data() {
    return {
      nextReqMessageID: "", //续拉消息ID
      conversationID: "", //用户id
      messageList: [],
    };
  },
  methods: {
    //获取消息列表
    getMessageList() {
      uni.$TUIKit
        .getMessageList({
          conversationID: this.conversationID,
          nextReqMessageID: this.nextReqMessageID,
        })
        .then((res) => {
          this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
          let arr = [];
          res.data.messageList.forEach((val) => {
            arr.unshift(val);
          });
          this.messageList = [...arr, ...this.messageList];
        });
    },
    //下拉加载更多
    scrolltoupper() {
      if (this.nextReqMessageID) {
        this.getMessageList();
      }
    },
    //更新已读
    setMessageRead() {
      uni.$TUIKit
        .setMessageRead({
          conversationID: this.conversationID,
        })
        .then(function () {
          // 发送C2C消息已读回执成功
        })
        .catch(function (imError) {
          // 发送C2C消息已读回执失败
        });
    },
    //收到消息
    receiveAMessage(event) {
      this.messageList = [...event.data, ...this.messageList];
    },
  },
  onLoad(options) {
    this.conversationID = options.conversationID;
    this.getMessageList();
    this.setMessageRead();
    uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.receiveAMessage);
  },
  components: {
    realName,
  },
  destroyed() {
    // 一定要解除相关的事件绑定
    uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.receiveAMessage);
  },
};
</script>

<style lang="scss" scoped>
.scroll {
  box-sizing: border-box;
  padding: 20rpx;

  .message {
  }
}
</style>